import sys
from st2common.runners.base_action import Action

from lib.rabbitmq import get_broker_from_kwargs


class CmdbAction(Action):

    def __init__(self, config=None, action_service=None):
        super(CmdbAction, self).__init__(config, action_service)

        config = self.config.get('task_sensor_config')
        if config:
            self.broker, self.queues = get_broker_from_kwargs(self.logger ,**config)
        else:
            self.broker = None
            self.queues = None

    def run(self, **kwargs):
        self.logger.info("class {} receive message {}".format(self.__class__.__name__, kwargs))
        self.logger.info("class {} config {}".format(self.__class__.__name__, self.config))
        self.publish(kwargs.get('payload', {}))
        sys.exit(0)

    def publish(self, payload):
        if not self.broker:
            self.logger.error("class {} publish not broker, publish {}".format(self.__class__.__name__, payload))
            return
        for queue in self.queues:
            self.broker.publish('eop', queue, payload)

    def cleanup(self):
        self.broker.close()
